#-*- coding:utf8 -*-
import os
from tornado import database
import struct,socket
from lib import session
import datetime

settings = {
    "template": os.path.join(os.path.dirname(__file__), "template/default"),
    "session": os.path.join(os.path.dirname(__file__), "temp/session"),
    "db": {
           "host": "localhost",
           "name": "a3",
           "uname": "root",
           "pwd": "123456"
    }
}

session.Session.setPath(settings['session'])
conn = None
def getDBConnect():
    global conn
    if not conn:
        conn = database.Connection(host=settings['db']['host'], user=settings['db']['uname'], 
                                   password=settings['db']['pwd'], database=settings['db']['name'])
    else:
        try:
            conn.ping()
        except:
            conn.reconnect()
    return conn

def ip2bigint(ip):
    return struct.unpack("!L",socket.inet_aton(ip))[0]

def time_from_now(t):
    if not isinstance(t, int):
        t = int(t)
    t = datetime.datetime.fromtimestamp(t)
    today = datetime.datetime(year=t.year, month=t.month, day=t.day)
    time_diff = datetime.datetime.utcnow() + datetime.timedelta(hours=8) - today
    if time_diff.days:
        return t.strftime('%Y-%m-%d')
    else:
        return t.strftime('%H:%M')